package com.alangyun.remind.config;

import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.alangyun.remind.RemindPreference;
import com.alangyun.remind.controller.Paths;
import com.alangyun.remind.utils.Utility;

@Configuration
@DependsOn("remind-pref")
public class RemindWebConfiguration implements WebMvcConfigurer {
	
    @Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String loc= RemindPreference.getUploadRootPath();
		if(!loc.endsWith("/"))
			loc+="/";
		if(!loc.toUpperCase().startsWith("FILE:"))
			loc="file:"+loc;
		registry.addResourceHandler(Paths.UPLOAD_CONTEXT_PATH_PATTERN).addResourceLocations(loc);
		WebMvcConfigurer.super.addResourceHandlers(registry);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		WebMvcConfigurer.super.addInterceptors(registry);
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		WebMvcConfigurer.super.configureMessageConverters(converters);
	    converters.add(responseBodyConverter());
	}
	
	@Bean
    public HttpMessageConverter<?> responseBodyConverter(){
		//对controller的字符集支持
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }
	
	/**
	 *  统一解析日期，jackson只对对象包进行序列化和反序列化才有效，<br/>
	 *  通过controller或restcontroller传递的参数，设置jackson无效
	 * @create hoobort
	 * @date 2019年4月29日 上午7:25:37
	 * @return
	 */
	@Bean
	public Converter<String,Date> createDateFormatConverter(){
		return new Converter<String,Date>(){
			
			@Override
			public Date convert(String source) {
				DateFormat format= new SimpleDateFormat(source.indexOf(':')>0?Utility.DATETIME_FORMAT:Utility.DATE_FORMAT);
				Date ret= null;
				try {
					ret= format.parse(source);
				}catch(ParseException ex) {
					ex.printStackTrace();
				}
				
				return ret;
			}
			
		};
	}

}
